<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\Articletype;
use app\admin\model\City;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopjoin;
use app\admin\model\Shopmeituan;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoptuan;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\MeituanService;
use app\api\service\MtService;
use app\api\service\MtUtil;
use app\api\service\XhtMtService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;

/**
 */
class Mt extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $appKey = "";
    protected $secret = "";
    public function _initialize()
    {
        parent::_initialize();
        $this->appKey = "2c8bce9314172fc1";
        $this->secret = "bb39c01023ce0fbb519d2b68f4457ec37fbc0e6a";
    }

    public function checkCode(){

        $user = $this->auth->getUser();
        $code = $this->request->param('code');
        $shop_id = $this->request->param('shop_id');
        $type = $this->request->param('type');
        if(!$type){
            $type = 'qp';
        }

        $req = array();
        $code = str_replace(" ", "", $code);
        $req['code'] = trim($code);

        $req['shop_id'] = $shop_id;


        $shopModel = new Shop();
        $shop = $shopModel->where('id',$shop_id)->find();

        if($shop['is_sync'] == 1){
            if($shop['mt2_token'] != ""){
                $meituanService = new MeituanService();
                $mtInfo = $meituanService->prepare($req);
            }else{
                $mtService = new MtService();
                $mtInfo = $mtService->couponInfo($req);
            }
//            $mtService = new MtService();
//            $mtInfo = $mtService->couponInfo($req);

        }else{
            $mtService = new XhtMtService();
            $mtInfo = $mtService->couponInfo($req);
        }


        if($mtInfo['code'] != 200){
            $this->error($mtInfo['msg']);
        }

        $meituanUserCodeModel = new Usermeituancode();

        $mtCode = $meituanUserCodeModel->where('mt_code',$code)->find();
        if($mtCode['status'] == 'unuse'){
            $meituanUserCodeModel->where('id',$mtCode['id'])->delete();
            $mtCode = $meituanUserCodeModel->where('mt_code',$code)->find();
        }
        $meituanModel = new Shopmeituan();
        $meituan = $meituanModel->where('shop_id',$shop_id)->where('dealgroup_id',$mtInfo['data']['dealgroup_id'])->find();
        if(!$mtCode){
           $id =  $meituanUserCodeModel->insertGetId(['user_id'=>$user['id'],'mt_code'=>$code,
                'create_time'=>time(),'status'=>'unuse','order_id'=>-1,'group_id'=>$meituan['id'],'shop_id'=>$meituan['shop_id']]);
        }else{
           $id =  $mtCode['id'];
        }
        $this->success('',$id);
    }

    public function checkCodeHour()
    {

        $user = $this->auth->getUser();
        $code = $this->request->param('code');
        $shop_id = $this->request->param('shop_id');
        $type = $this->request->param('type');
        if (!$type) {
            $type = 'qp';
        }

        $req = array();
        $code = str_replace(" ", "", $code);
        $req['code'] = trim($code);

        $req['shop_id'] = $shop_id;

        $shopModel = new Shop();
        $shop = $shopModel->where('id', $shop_id)->find();

        if ($shop['is_sync'] == 1) {
            if ($shop['mt2_token'] != "") {
                $meituanService = new MeituanService();
                $mtInfo = $meituanService->prepare($req);
            } else {
                $mtService = new MtService();
                $mtInfo = $mtService->couponInfo($req);
            }
//            $mtService = new MtService();
//            $mtInfo = $mtService->couponInfo($req);

        } else {
            $mtService = new XhtMtService();
            $mtInfo = $mtService->couponInfo($req);
        }


        if ($mtInfo['code'] != 200) {
            $this->error($mtInfo['msg']);
        }

        $meituanUserCodeModel = new Usermeituancode();

        $mtCode = $meituanUserCodeModel->where('mt_code', $code)->find();
        if ($mtCode['status'] == 'unuse') {
            $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
            $mtCode = $meituanUserCodeModel->where('mt_code', $code)->find();
        }
        $meituanModel = new Shopmeituan();
        $meituan = $meituanModel->where('shop_id', $shop_id)->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
        if (!$mtCode) {
            $id = $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $code,
                'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);

        } else {
            $id = $mtCode['id'];
        }
        $hour = $meituan['hour'];

        $db = array();
        $db['id'] = $id;
        $db['hour'] = $hour;
        $this->success('', $db);
    }

    public function userCodeDetail(){
        $id = $this->request->param('id');
        $shop_id = $this->request->param('shop_id');
        $meituanUserCodeModel = new Usermeituancode();
        $where = array();

        $mtCode = $meituanUserCodeModel->where('id',$id)->find();
        if(!$shop_id){
            $shop_id = $mtCode['shop_id'];
        }
        if($shop_id != ""){
            $where['shop_id'] = $shop_id;
        }
        $meituanModel = new Shopmeituan();
        $meituan = $meituanModel->where($where)->where('id',$mtCode['group_id'])->find();

        $deal_id = $meituan['deal_id'];
        $meituan = $meituanModel->where($where)->where('deal_id',$deal_id)->find();

        $shopModel = new Shop();
        $shop = $shopModel->where('id',$meituan['shop_id'])->find();
        if(!$shop) $this->error("请联系商家，此券未关联系统");
        $roomModel = new Shoproom();
        $tableModel = new \app\admin\model\Shoptable();
        $rooms = json_decode($meituan['room_id'],true);
        $array = array();
        foreach ($rooms as $key=>$val){
            if($meituan['type'] == 'tq'){
                $room = $tableModel->where('id',$val)->find();
            }else{
                $room = $roomModel->where('id',$val)->find();

            }
            $array[] = $room;
        }

        $ret = array();
        $ret['code'] = $mtCode['mt_code'];
        $ret['title'] = $meituan['title'];
        $ret['hour'] = $meituan['hour'];
        $ret['shopName'] = $shop['name'];
        $ret['shop_id'] = $meituan['shop_id'];

        $ret['roomName'] = $array;
        $ret['type'] = $meituan['type'];

        $this->success('',$ret);

    }

    public function callback(){
        $param = file_get_contents("php://input");
        error_log("==mt=callback===".json_encode($param));
    }



    /* @FunctionDesc:美团卡卷 查询、验券（核销），撤销验券
     * @Params:  qr_code 卡券券码
     *           open_shop_uuid 店铺id (根据session值 获取得到)
     *           deal_id 套餐id 查询接口获得
     *           type 功能类型 值为 save 验券（核销）、值为 cancel 验券（核销）、其他值时为查询
     * */

    public function couponInfo(){

        $qr_cpde = $this->request->param('code');
        $shop_id = $this->request->param('shop_id');
        $shopModel = new Shop();
        $shop  = $shopModel->where('id',$shop_id)->find();
        $open_shop_uuid = $shop['open_shop_uuid'];
        $mtUtil = new MtUtil();
        $appKey = $this->appKey;
        $secret = $this->secret; //秘钥
        $timestamp = date('Y-m-d H:i:s');
        $format = 'json';
        $v = 1;
        $sign_method = 'MD5';

        $data = [
            'app_key' => $appKey,
            'timestamp' => $timestamp,
            'sign_method' => $sign_method,
            'format' => $format,
            'session'=>$shop['mt_token'],
            'v' => $v,

        ];
        $arr = [
            'receipt_code' => $qr_cpde,
            'open_shop_uuid' => $open_shop_uuid,
        ];
        $url = 'https://openapi.dianping.com/router/tuangou/receipt/prepare';//查询券
        $data = array_merge($data, $arr);
        ksort($data);
        $sign = $mtUtil->call_sign($secret, $data);//获取签名
        $data['sign'] = $sign;
        $data = array_merge($data, $arr);
        $postdata = http_build_query($data);
        $tmpInfo= $mtUtil->curl_post($url,$postdata);

        $this->success('',$tmpInfo);
    }

    public function tuangou_hexiao(){
        //
        $qr_cpde = $_GET['qr_code'];
        $open_shop_uuid = $_GET['open_shop_uuid'];
        $mtUtil = new MtUtil();
        // $arr 为数组 里面为应用参数
        $appKey = $this->appKey;
        $secret = $this->secret; //秘钥
        $timestamp = date('Y-m-d H:i:s');
        $format = 'json';
        $v = 1;
        $sign_method = 'MD5';
        $data = [
            'app_key' => $appKey,
            'timestamp' => $timestamp,
            'sign_method' => $sign_method,
            'format' => $format,
            'v' => $v,
            //此处的session值，我原本是存在文件中的，
            //如果你不需要存文件，那你就当做参数传递过来
            //'session' => $file['session'],
        ];
        //根据不同的操作类型配置不同的参数
        //具体参数含义见 https://open.dianping.com/document/v2?docId=6000176&rootDocId=5000
        if($_GET['type']=='save'){
            $arr = [
                'requestid' => '123',
                'count'=>1,
                'receipt_code' => $qr_cpde,
                'open_shop_uuid' => $open_shop_uuid,
                'app_shop_account' => '账号',
                'app_shop_accountname' => '账号名称',
            ];
            $url = 'https://openapi.dianping.com/router/tuangou/receipt/consume';//验券(核销)
        }elseif ($_GET['type']=='cancel'){
            $arr = [
                'app_deal_id' => $_GET['deal_id'],
                'receipt_code' => $qr_cpde,
                'open_shop_uuid' => $open_shop_uuid,
                'app_shop_account' => '账号',
                'app_shop_accountname' => '账号名称',
            ];
            $url = 'https://openapi.dianping.com/router/tuangou/receipt/reverseconsume';//撤销
        }else{
            $arr = [
                'receipt_code' => $qr_cpde,
                'open_shop_uuid' => $open_shop_uuid,
            ];
            $url = 'https://openapi.dianping.com/router/tuangou/receipt/prepare';//查询券
        }

        $data = array_merge($data, $arr);
        ksort($data);
        $sign = $mtUtil->call_sign($secret, $data);//获取签名
        $data['sign'] = $sign;
        $data = array_merge($data, $arr);
        $postdata = http_build_query($data);
        $tmpInfo= $mtUtil->curl_post($url,$postdata);

        return $tmpInfo;
    }

    /* @FunctionDesc:商家授权
     * @Params:  auth_code 用户同意授权后，回调得到的值，根据该值可获取session(也就是auth_token)
     * */
    public function auth(){
        $auth_code = $_GET["auth_code"];
        $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/mt/auth";

        //判断是否为回调
        if(empty($auth_code)) {
            $app_key=$this->appKey;
            $state='teststate';
            //回调的url,我配置为当前方法。
            $redirect_url=$url;
            $url='https://e.dianping.com/dz-open/merchant/auth?';
            $data=[
                'app_key' =>$app_key,
                'state' => $state,
                'redirect_url'=>$redirect_url
            ];
            $postdata = http_build_query($data);
            header("Location: $url$postdata");
        } else {

            $tmpInfo = $this->shopSession($auth_code);
            error_log("======tmpInfo==".json_encode($tmpInfo));

            //根据$session $bid 获取店铺id
            $shopInfo = $this->getShopId($tmpInfo['access_token'],$tmpInfo['bid']);
            $data = $shopInfo['data'];
            $shopModel = new Shop();
            $expires_in = $tmpInfo['expires_in'];
            $min = intval($expires_in/60);
            //error_log($min."==========".$expires_in);
            $updateTime =strtotime("+".$min." minutes",time());
            foreach ($data as $key=>$val){
                $open_shop_uuid =   $val['open_shop_uuid'];
                $name = $val['shopname'];
                $branchname= "";
                if(isset($val['branchname'])){
                    $branchname = $val['branchname'];
                }
                if($branchname != ""){
                    $shop = $shopModel->where('mt_name',$name."(".$branchname.")")->find();
                }else{
                    $shop = $shopModel->where('mt_name',$name)->find();

                }
                if($shop){
                    $shopModel->where('id',$shop['id'])->update(['open_shop_uuid'=>$open_shop_uuid,'mt_token'=>$tmpInfo['access_token'],'mt_update_time'=>$updateTime,'mt_refresh_token'=>$tmpInfo['refresh_token']]);
                }
            }
            error_log("======shopInfo====".json_encode($shopInfo));
            $this->success('授权成功');
        }
    }


    //授权获取session
    public function shopSession($auth_code){
        $mtUtil = new MtUtil();

        $app_key=$this->appKey;
        $app_secret=$this->secret;
        $grant_type='authorization_code';
        $redirect_url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/mt/auth";

        $data=[
            'app_key' =>$app_key,
            'app_secret' => $app_secret,
            'redirect_url' =>$redirect_url,
            'auth_code' =>$auth_code,
            'grant_type' =>$grant_type
        ];
        $postdata = http_build_query($data);
        $url='https://openapi.dianping.com/router/oauth/token';
        $tmpInfo=$mtUtil->curl_post($url,$postdata);
        return $tmpInfo;
    }


    //获取所有店铺的id
    public function getShopId($session,$bid){
        $mtUtil = new MtUtil();
        $app_key=$this->appKey;
        $secret = $this->secret; //秘钥
        $sign_method='MD5';
        $timestamp = date('Y-m-d H:i:s');
        $format = 'json';
        $v = 1;
        $offset =0;
        $limit = 20;
        $url='https://openapi.dianping.com/router/oauth/session/scope?';
        $data=[
            'app_key' =>$app_key,
            'sign_method' => $sign_method,
            'timestamp' =>$timestamp,
            'format' =>$format,
            'v' =>$v,
            'session' =>$session,
            'bid' =>$bid,
            'offset' =>$offset,
            'limit' =>$limit,
        ];
        error_log("===session==".json_encode($session));
        ksort($data);
        $sign = $mtUtil->call_sign($secret, $data);
        $data['sign'] = $sign;
        $postdata = http_build_query($data);
        $tmpInfo=$mtUtil->curl_get($url.$postdata);
        return $tmpInfo;
    }



    public function refreshToken(){



        $time = strtotime("+1 day",time());
        //$time = time();
        $shopListModel = new Shop();
        $list = $shopListModel->where('mt_update_time',"<=",$time)->select();


        error_log("==mt=list=".json_encode($list));
        foreach ($list as $key=>$val){

            if($val['open_shop_uuid'] != "" ){
                $mtUtil = new MtUtil();
                $data=[
                    'app_key' =>$this->appKey,
                    'app_secret' => $this->secret,
                    'grant_type' =>'refresh_token',
                    'refresh_token' =>$val['mt_refresh_token']
                ];

                error_log($val['id']."===reqdata==".json_encode($data));
                $postdata = http_build_query($data);
                $url='https://openapi.dianping.com/router/oauth/token';
                $tmpInfo=$mtUtil->curl_post($url,$postdata);
                error_log("==refresh=token=".json_encode($tmpInfo));
                if($tmpInfo['code'] == 200){
                    $token = $tmpInfo['access_token'];
                    $refreshToken = $tmpInfo['refresh_token'];

                    $remain_refresh_count = $tmpInfo['remain_refresh_count'];
                    $shopListModel->where('id',$val['id'])->update(['mt_token'=>$token,'mt_count'=>$remain_refresh_count,'mt_update_time'=>time(),'mt_refresh_token'=>$refreshToken]);
                }

            }



        }

        $this->success("成功",$list);

    }


    public function refreshToken2(){



        //$time = time();
        $shopListModel = new Shop();
        $list = $shopListModel->where('id',1)->select();


        error_log("==mt=list=".json_encode($list));
        foreach ($list as $key=>$val){

            if($val['open_shop_uuid'] != "" ){
                $mtUtil = new MtUtil();
                $data=[
                    'app_key' =>$this->appKey,
                    'app_secret' => $this->secret,
                    'grant_type' =>'refresh_token',
                    'refresh_token'=>$val['mt_refresh_token']
                ];

                error_log($val['id']."===reqdata==".json_encode($data));
                $postdata = http_build_query($data);
                $url='https://openapi.dianping.com/router/oauth/token';
                $tmpInfo=$mtUtil->curl_post($url,$postdata);
                error_log("==refresh=token=".json_encode($tmpInfo));
                if($tmpInfo['code'] == 200){
                    $token = $tmpInfo['access_token'];
                    $refreshToken = $tmpInfo['refresh_token'];

                    $remain_refresh_count = $tmpInfo['remain_refresh_count'];
                    $shopListModel->where('id',$val['id'])->update(['mt_token'=>$token,'mt_count'=>$remain_refresh_count,'mt_update_time'=>time(),'mt_refresh_token'=>$refreshToken]);
                }

            }



        }

        $this->success("成功");

    }

    public function syncNew()
    {
        $shopModel = new Shop();
        $mt_shop_name = $this->request->param('mt_shop_name');
        $open_shop_uuid = $this->request->param('open_shop_uuid');
        $mt_token = $this->request->param('mt_token');
        $mt_update_time = $this->request->param('mt_update_time');
        $mt_refresh_token = $this->request->param('mt_refresh_token');
       //
        $shop = $shopModel->where('open_shop_uuid',$open_shop_uuid)->find();
        if($shop){
            $shopModel->where('id',$shop['id'])->update(['open_shop_uuid'=>$open_shop_uuid,'mt_token'=>$mt_token,'mt_update_time'=>$mt_update_time,'mt_refresh_token'=>$mt_refresh_token]);
        }else{
            $shop = $shopModel->where('mt_name',$mt_shop_name)->find();
            if($shop){
                $shopModel->where('id',$shop['id'])->update(['open_shop_uuid'=>$open_shop_uuid,'mt_token'=>$mt_token,'mt_update_time'=>$mt_update_time,'mt_refresh_token'=>$mt_refresh_token]);
            }
        }
    }

}
